﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using XEvent.Interface;

namespace XEvent.Ioc
{
    public class XContainerImpl : IXContainer
    {
        private IDictionary<Type, object> _serviceRegistry = new Dictionary<Type, object>();

        public void Register<TService>() where TService : class, new()
        {
            _serviceRegistry[typeof(TService)] = new Func<TService>(() => new TService());
        }

        public void Register<TService>(Func<TService> factory) where TService : class
        {
            _serviceRegistry[typeof(TService)] = factory;
        }

        public TService Resolve<TService>() where TService : class, new()
        {
            if (_serviceRegistry.ContainsKey(typeof(TService)))
            {
                var service = _serviceRegistry[typeof(TService)];
                var func = service as Func<TService>;
                return func();
            }
            else
            {
                throw new InvalidOperationException($"No service of type {typeof(TService).Name} has been registered.");
            }
        }
    }
}
